`include "vga_param.v"

module vga_driver(
    //Inputs
     input clk          
    ,input [15:0] rgb_data
    ,input rst_n

    //Outputs
    ,output [11:0] pos_x        //0 ~ WIDTH - 1
    ,output [11:0] pos_y        //0 ~ HEIGHT -1
    
    ,output [15:0] vga_data
    ,output vga_hsync
    ,output vga_vsync
);

reg [11:0] cnt_h = 0;
reg [11:0] cnt_v = 0;

wire h_valid = (cnt_h > (`VGA_HA + `VGA_HB)) & (cnt_h <= (`VGA_HE - `VGA_HD));
wire v_valid = (cnt_v > (`VGA_VO + `VGA_VP)) & (cnt_v <= (`VGA_VS - `VGA_VR));
wire rgb_valid = h_valid & v_valid;

assign vga_hsync = (cnt_h > `VGA_HA) ? 1 : 0;
assign vga_vsync = (cnt_v > `VGA_VO) ? 1 : 0;
assign pos_x = h_valid ? (cnt_h - `VGA_HA - `VGA_HB) : 'h0;
assign pos_y = v_valid ? (cnt_v - `VGA_VO - `VGA_VP - 1) : 'h0;
assign vga_data[15:0] = rgb_valid ? rgb_data : 16'd0;

always @ (posedge clk) begin
    if(!rst_n) begin
        cnt_h <= 'd1;
        cnt_v <= 'd1;
    end
    else begin
        if(cnt_h == `VGA_HE)
            cnt_h <= 1;
        else 
            cnt_h <= cnt_h + 1;
        
        if(cnt_h == `VGA_HE) begin
            if(cnt_v == `VGA_VS)
                cnt_v <= 1;
            else 
                cnt_v <= cnt_v + 1;
        end
    end
end

endmodule
